<template>
  <z-modal
    :title="title"
    v-bind="modalOption"
    :bodyStyle="{minHeight:'500px','padding-top':'0px'}"
    @cancel="handleCancel"
  >
    <template slot="footer">
      <div style="text-align:center;">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" v-if="type !== 'history'" :loading="confirmLoading" @click="handleComplete">签核</a-button>
        <a-button type="danger" v-if="type !== 'history'" ghost :loading="confirmLoading" @click="handleRejectLast">驳回上一节点</a-button>
        <a-button type="danger" v-if="type !== 'history'" ghost :loading="confirmLoading" @click="handleRejectFirst">退回</a-button>
      </div>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-tabs  tab-position="left">
        <a-tab-pane key="1">
          <span slot="tab">
            <a-icon type="file" />
            表单信息
          </span>
          <a-collapse v-model="activeKey" class="!mt-4">
            <a-collapse-panel key="1" header="发起单据">
              <KFormBuild class="k-form-design" ref="kfbStart" :dynamicData="dynamicDataSatrt" disabled :value="formModel" />
            </a-collapse-panel>
            <a-collapse-panel key="2" header="待办单据" v-if="hasTaskForm && type !== 'history'">
              <TaskForm class="k-form-design" ref="kfbPend" :task="task" :formData="formData" :nodeId="task.taskDefinitionKey" @init="taskFormInit" />
            </a-collapse-panel>
          </a-collapse>
        </a-tab-pane>
        <a-tab-pane key="2">
          <span slot="tab">
            <a-icon type="share-alt" />
            办理进度
          </span>
          <bpmnTaskViewer :xml="flowDef.source"/>
        </a-tab-pane>
        <a-tab-pane key="3" >
          <span slot="tab">
            <a-icon type="history" />
            办理记录
          </span>
          <TaskHistory :processInstanceId="task.processInstanceId" :formData="formData" />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </z-modal>
</template>

<script>
import ModalMixins from '@/mixins/ModalMixins'
import { postAction, getAction } from '@/services/manage'
import { KFormBuild } from '@/components/k-form-design/packages/use.js'
import bpmnTaskViewer from '@/components/bpmn/bpmnTaskViewer'
import TaskHistory from './TaskHistory'
import TaskForm from './TaskForm'
import { getSelectDictCode, getSelectOptions } from '@/utils/k-form-design'
export default {
  name: 'TaskPendingModal',
  components: { KFormBuild, bpmnTaskViewer, TaskHistory, TaskForm },
  mixins: [ModalMixins],
  props: {
    type: String
  },
  data() {
    return {
      url: {
        flowDef: '/camunda/process/details/',
        complete: '/camunda/task/complete/',
        rejectlast: '/camunda/task/reject/last/',
        rejectfirst: '/camunda/task/reject/first/'
      },
      formModel: { }, // 表单设计model
      task: {}, // 任务信息
      formDef: {}, // 表单设计信息
      flowDef: {}, // 流程设计信息
      formData: {}, // 表单数据信息
      title: '流程办理',
      activeKey: ['1', '2'],
      dynamicDataSatrt: {},
      hasTaskForm: true
    }
  },
  methods: {
    show(task) {
      this.task = task
      this.getflowForm()
      this.visible = true
    },
    taskFormInit(hasTaskForm) {
      console.log('hasTaskForm', hasTaskForm)
      this.hasTaskForm = hasTaskForm
    },
    handleComplete() {
      if (this.hasTaskForm && this.$refs.kfbPend) {
        this.$refs.kfbPend.getData().then(values => {
          console.log('验证通过', values)
          this.complete(values)
        }).catch(() => {
          console.log('验证未通过，获取失败')
        })
      } else {
        this.complete({})
      }
    },
    complete(data) {
      postAction(this.url.complete + this.task.id, data).then(res => {
        if (res.success) {
          this.$message.success('签核成功')
          this.close()
          this.$emit('ok')
        }
      })
    },
    handleRejectLast() {
      if (this.hasTaskForm && this.$refs.kfbPend) {
        this.$refs.kfbPend.getData().then(values => {
          console.log('验证通过', values)
          this.rejectLast(values)
        }).catch(() => {
          console.log('验证未通过，获取失败')
        })
      } else {
        this.rejectLast({})
      }
    },
    rejectLast(data) {
      postAction(this.url.rejectlast + this.task.id, data).then(res => {
        if (res.success) {
          this.$message.success('驳回上一节点成功')
          this.close()
          this.$emit('ok')
        }
      })
    },
    handleRejectFirst() {
      if (this.hasTaskForm && this.$refs.kfbPend) {
        this.$refs.kfbPend.getData().then(values => {
          console.log('验证通过', values)
          this.rejectFirst(values)
        }).catch(() => {
          console.log('验证未通过，获取失败')
        })
      } else {
        this.rejectFirst({})
      }
    },
    rejectFirst(data) {
      postAction(this.url.rejectfirst + this.task.id, data).then(res => {
        if (res.success) {
          this.$message.success('退回成功')
          this.close()
          this.$emit('ok')
        }
      })
    },
    async getflowForm() { // 根据流程定义id获取绑定表单-发起单据及流程
      try {
        this.confirmLoading = true
        const res = await getAction(this.url.flowDef + this.task.processInstanceId)
        if (!res.success) {
          this.confirmLoading = false
          return this.$message.warning('未查询到发起表单')
        }
        const formModel = res.result.startFormModelDef && res.result.startFormModelDef.model && JSON.parse(res.result.startFormModelDef.model)

        // 必须在渲染前获取到dynamicData --start
        let dictCodes = getSelectDictCode(formModel.list)
        dictCodes = Array.from(new Set(dictCodes))
        this.dynamicDataSatrt = await getSelectOptions(dictCodes)
        // -- end

        // formModel.list = replaceFormModel(formModel.list)

        this.formModel = formModel
        this.flowDef = res.result
        this.formDef = res.result.formModelDef
        this.formData = res.result.startDatas
        this.$nextTick(() => {
          // const data = {
          //   '${nodeId}input_1686714173341': '1233',
          //   'textarea_1686714174101': '',
          //   'VXETable_1690425486881': [
          //     {
          //       'input_1690440088498': '11222eerr',
          //       'select_1690425487886': '1',
          //       '_X_ROW_KEY': 'row_171'
          //     }
          //   ],
          //   'batch_1690447073903': [
          //     {
          //       'input_1690447075980': '',
          //       'key': 'g8pqt40hcm000'
          //     }
          //   ]
          // }
          // this.$refs.kfbStart.setData(data)
          const startDatas = res.result.startDatas
          Object.keys(startDatas).forEach(key => {
            this.isJsonString(startDatas[key]) ? startDatas[key] = JSON.parse(startDatas[key]) : ''
          })
          this.$refs.kfbStart.setData(startDatas)
        })
        this.confirmLoading = false
      } catch (error) {
        this.confirmLoading = false
      }
    },
    isJsonString(str) {
      try {
        const toObj = JSON.parse(str) // json字符串转对象
        /*
          判断条件
          1. 排除null可能性
          2. 确保数据是对象或数组
        */
        if (toObj && typeof toObj === 'object') {
          return true
        }
      } catch {
        console.error('err')
      }
      return false
    }
  }
}
</script>
